package xiaolong.arithmetic.fun_lib;

/**
 * Created by xinxiaolong on 2020/11/30.
 * email：xinxiaolong123@foxmail.com
 * <p>
 * 编写一个函数来查找字符串数组中的最长公共前缀。
 * <p>
 * 如果不存在公共前缀，返回空字符串 ""。
 * <p>
 * 示例 1:
 * <p>
 * 输入: ["flower","flow","flight"]
 * 输出: "fl"
 * 示例 2:
 * <p>
 * 输入: ["dog","racecar","car"]
 * 输出: ""
 * 解释: 输入不存在公共前缀。
 * <p>
 * 链接：https://leetcode-cn.com/problems/longest-common-prefix
 */
public class Longest {

    public static void main(String[] ags) {
        String[] strings={};
        String same=longestCommonPrefix(strings);
        System.out.print(same);
    }

    public static String longestCommonPrefix(String[] str) {
        if (str == null||str.length==0) {
            return "";
        }
        if(str.length <=1){
            return str[0];
        }

        String same = str[0];
        for (int i = 0; i < str.length-1; i++) {
            same = sameText(same, str[i + 1]);
            if (same.length() == 0) {
                return "";
            }
        }
        return same;
    }

    public static String sameText(String str1, String str2) {
        if(str1.length()==0||str2.length()==0){
            return "";
        }
        StringBuilder buffer=new StringBuilder();
        char[] chars=str1.toCharArray();
        for (int i=0;i<chars.length;i++){
            if(str2.length()-1>=i&&chars[i]==str2.charAt(i)){
                buffer.append(chars[i]);
            }else {
                break;
            }
        }
        return buffer.toString();
    }

}
